<?php
// 通过事物控制方案1：将shop_list表商品数量字段字段nums字段设为unsigned，当库存为0时，因为字段不能为负数，将会返回false
$dbms='mysql';     //数据库类型
$host='127.0.0.1'; //数据库主机名
$dbName='fastbuy';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";

try {
    $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    echo "连接成功<br/>";
    // 你还可以进行一次搜索操作
    // $dbh = null;
} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}

//生成唯一订单
function build_order_no(){
    // return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return date('ymdhis').uniqid();
}
//记录日志
function insertLog($dbh,$message){
    $time = date("Y-m-d H:i:s");
    $sql="insert into log(content,addtime) 
    values('$message','$time')";
    $dbh->exec($sql);
    
}

$userid = $_REQUEST["userid"];
$shop_id = $_REQUEST["shop_id"];

$userid = 1;
$shop_id = 1;

// 查询商品是否还有库存
$sql = "select * from shop_list where id = '$shop_id'";
$res = $dbh->query($sql);
$shopArr = $res->fetch();
$shopNum = $shopArr["nums"];  // 商品数量
$shopMoney = $shopArr["money"];  // 商品价格

// 判断商品数量
if($shopNum > 0){
    // 检查用户账户金额
    $sql = "select * from user_info where id = '$userid'";
    $res = $dbh->query($sql);
    $userArr = $res->fetch();
    $userMoney = $userArr["money"];  // 用户金额

    // 用户金额不足支付
    if($userMoney >= $shopMoney){  
        // 减去库存
        $sql= "update shop_list set nums = nums - 1 where id = '$shop_id'";
        $num = $dbh->exec($sql);
        if($num){
            // 更新账户金额
            $sql = "update user_info set money = money - $shopMoney where id = '$shop_id'";
            $num = $dbh->exec($sql);

            // 记录抢购信息
            $time = date("Y-m-d H:i:s");
            $orderid = build_order_no();
            $sql = "insert into buy_record (`userid`,`orderid`,`shop_id`,`time`) value ('$userid','$orderid','$shop_id','$time')";
            $num = $dbh->exec($sql);
            insertLog($dbh,"抢购成功");
        } else {
            insertLog($dbh,"更新商品数量失败");
        }        
    } else {
        insertLog($dbh,"账户余额不足");
    }
}else{
    insertLog($dbh,"商品数量不足");
}
?>